import React from 'react';
import { Input, Icon } from 'antd';
import GlobalSearchList from './globalSearchList';

export default class SearchInput extends React.Component {

    state={
        value: '',
        focus: false,
    }

    onFocus = () => {
        this.setState({ focus: true });
    }

    onBlur = () => {
        this.onClear();
    }

    onClear = () => {
        // 回复默认值
        this.setState({ focus: false, value: '', searchkey: undefined }, () => {
            this.value = '';
            if(this.props.onClear) this.props.onClear();
        })
    }

    onChange = (e) => {
        this.setState({ value: e.target.value });
    }

    onPressEnter = (e) => {
        const { global, onPressEnter } = this.props;
        // 避免值相同重复触发
        const value = e.target.value;
        if(value === this.value) return;
        this.value = value;
        if(global) {
            this.setState({ searchkey: value });
        } else {
            onPressEnter(value);
        }
    }
  
    render(){
        const { placeholder, global } = this.props;
        const { focus, value, searchkey } = this.state;
        return (
            <>
                <Input
                    value={value}
                    placeholder={placeholder}
                    prefix={<Icon type="search" style={{ color: 'rgba(0,0,0,.25)' }} />}
                    suffix={focus ? <Icon type="close-circle" style={{ color: 'rgba(0,0,0,.25)' }} onClick={this.onClear}/> : null}
                    onFocus={this.onFocus}
                    // onBlur={this.onBlur}
                    onChange={this.onChange}
                    onPressEnter={this.onPressEnter}
                />
                {global && focus && searchkey ? <GlobalSearchList searchkey={searchkey} onClear={this.onClear} /> : null}
            </>
        )
    }  
}